<!--#layout name=mail-->
<div id="app">
  <div class="page-header">
    <h1 class="title">My addresses</h1>
  </div>
  <div class="navbar navbar-default">
    <div class="container-fluid">
      <a
        href="javascript:;"
        class="btn green navbar-btn"
        @click="modalType='Normal'"
        ><i class="fa fa-plus"></i> <span>Normal</span></a
      >
      <a
        href="javascript:;"
        class="btn green navbar-btn"
        @click="modalType='Wildcard'"
        ><i class="fa fa-plus"></i> <span>Wildcard</span></a
      >
      <a
        href="javascript:;"
        class="btn green navbar-btn"
        @click="modalType='Group'"
        ><i class="fa fa-plus"></i> <span>Group</span></a
      >
      <a
        href="javascript:;"
        class="btn green navbar-btn"
        @click="modalType='Forward'"
        ><i class="fa fa-plus"></i> <span>Forward</span></a
      >
      <a
        v-show="selectedRows.length"
        @click="onDelete"
        class="btn red navbar-btn"
        >Delete</a
      >
    </div>
  </div>
  <kb-table :data="model" show-select :selected.sync="selectedRows">
    <kb-table-column :label="Kooboo.text.mail.address.name" prop="address">
    </kb-table-column>
    <kb-table-column :label="Kooboo.text.common.useFor">
      <template v-slot="row">
        <span class="label" :class="row.useFor.class">{{row.useFor.text}}</span>
      </template>
    </kb-table-column>
    <kb-table-column :label="Kooboo.text.common.remark">
      <template v-slot="row">
        <a
          v-if="row.remark"
          class="label"
          :class="row.remark.class"
          @click.stop="editModal(row)"
          >{{row.remark.text}}</a
        >
      </template>
    </kb-table-column>
    <kb-table-column width="10px" align="rigth">
      <template v-slot="row">
        <a
          class="btn btn-xs blue"
          :title="Kooboo.text.mail.jumpToInbox"
          @click.stop=""
          :href="getInboxUrl(row)"
          ><i class="fa fa-inbox"></i
        ></a>
      </template>
    </kb-table-column>
  </kb-table>

  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button data-dismiss="modal" class="close"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">
            <span v-if="modalType=='Normal'||modalType=='Wildcard'"
              >New address</span
            >
            <span v-if="modalType=='Group'">New group</span>
            <span v-if="modalType=='EditForward'">Edit forwarding</span>
            <span v-if="modalType=='Forward'">New forwarding</span>
            <span v-if="modalType=='Members'">Group members</span>
          </h4>
        </div>
        <div class="modal-body" v-if="showModal">
          <kb-form
            v-if="modalType=='Normal'"
            :model="normalModel"
            :rules="normalModelRules"
            ref="normalForm"
          >
            <kb-form-item prop="local">
              <label class="control-label col-md-2">Address</label>
              <div class="col-md-10">
                <div class="input-group">
                  <input
                    type="text"
                    class="form-control"
                    v-model="normalModel.local"
                  />
                  <span class="input-group-addon">@</span>
                  <select class="form-control" v-model="normalModel.domain">
                    <option
                      v-for="(item,index) in domains"
                      :key="index"
                      :value="item.domainName"
                      >{{item.domainName}}</option
                    >
                  </select>
                </div>
              </div>
            </kb-form-item>
          </kb-form>
          <kb-form
            v-if="modalType=='Wildcard'"
            :model="wildcardModel"
            :rules="wildcardModelRules"
            ref="wildcardForm"
          >
            <div class="alert alert-info">
              <strong>Info</strong>
              <p>{{Kooboo.text.mail.wildcardTip}}</p>
            </div>
            <kb-form-item prop="local">
              <label class="control-label col-md-3">Wildcard address</label>
              <div class="col-md-9">
                <div class="input-group">
                  <input
                    type="text"
                    class="form-control"
                    v-model="wildcardModel.local"
                  />
                  <span class="input-group-addon">@</span>
                  <select class="form-control" v-model="wildcardModel.domain">
                    <option
                      v-for="(item,index) in domains"
                      :key="index"
                      :value="item.domainName"
                      >{{item.domainName}}</option
                    >
                  </select>
                </div>
              </div>
            </kb-form-item>
          </kb-form>

          <kb-form
            v-if="modalType=='Group'"
            :model="groupModel"
            :rules="groupModelRules"
            ref="groupForm"
          >
            <kb-form-item prop="local">
              <label class="control-label col-md-2">Group</label>
              <div class="col-md-10">
                <div class="input-group">
                  <input
                    type="text"
                    class="form-control"
                    v-model="groupModel.local"
                  />
                  <span class="input-group-addon">@</span>
                  <select class="form-control" v-model="groupModel.domain">
                    <option
                      v-for="(item,index) in domains"
                      :key="index"
                      :value="item.domainName"
                      >{{item.domainName}}</option
                    >
                  </select>
                </div>
              </div>
            </kb-form-item>
          </kb-form>
          <kb-form
            v-if="modalType=='Forward'"
            :model="forwardModel"
            :rules="forwardModelRules"
            ref="forwardForm"
          >
            <kb-form-item prop="local">
              <label class="control-label col-md-3">Agent address</label>
              <div class="col-md-9">
                <div class="input-group">
                  <input
                    type="text"
                    class="form-control"
                    v-model="forwardModel.local"
                  />
                  <span class="input-group-addon">@</span>
                  <select class="form-control" v-model="forwardModel.domain">
                    <option
                      v-for="(item,index) in domains"
                      :key="index"
                      :value="item.domainName"
                      >{{item.domainName}}</option
                    >
                  </select>
                </div>
              </div>
            </kb-form-item>
            <kb-form-item prop="forwardAddress">
              <label class="control-label col-md-3">Forward to address</label>
              <div class="col-md-9">
                <input
                  type="text"
                  class="form-control"
                  v-model="forwardModel.forwardAddress"
                />
              </div>
            </kb-form-item>
          </kb-form>
          <kb-form
            v-if="modalType=='EditForward'"
            :model="updateForwardModel"
            :rules="updateForwardModelRules"
            ref="editForwardForm"
          >
            <kb-form-item>
              <label class="control-label col-md-3">Agent address</label>
              <div class="col-md-9">
                <input
                  type="text"
                  class="form-control"
                  v-model="updateForwardModel.address"
                  disabled
                />
              </div>
            </kb-form-item>
            <kb-form-item prop="forwardAddress">
              <label class="control-label col-md-3">Forward to address</label>
              <div class="col-md-9">
                <input
                  type="text"
                  class="form-control"
                  v-model="updateForwardModel.forwardAddress"
                />
              </div>
            </kb-form-item>
          </kb-form>
          <template v-if="modalType=='Members'">
            <div class="navbar navbar-default">
              <div class="container-fluid">
                <a
                  href="javascript:;"
                  v-show="!editingMember"
                  @click="onEditMember"
                  class="btn green navbar-btn"
                  >Add</a
                >
              </div>
            </div>
            <table class="table table-striped table-hover">
              <thead>
                <tr>
                  <th>Address</th>
                  <th class="table-action"></th>
                  <th class="table-action"></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="($data,index) in members" :key="index">
                  <template v-if="!$data.editing">
                    <td>{{$data}}</td>
                    <td></td>
                    <td>
                      <a
                        href="javascript:;"
                        class="btn btn-xs red"
                        @click="removeMember($data)"
                        >Remove</a
                      >
                    </td>
                  </template>
                  <template v-else>
                    <td :class="{'has-error':$data.error}">
                      <input
                        type="text"
                        class="form-control"
                        v-model="$data.address"
                        @input="onMemberInput($data)"
                        v-kb-tooltip:left.manual.error="$data.error"
                      />
                    </td>
                    <td>
                      <a
                        href="javascript:;"
                        @click="saveMember($data)"
                        class="btn green"
                        >Save</a
                      >
                    </td>
                    <td>
                      <a
                        href="javascript:;"
                        class="btn gray"
                        @click="cancelMember($data)"
                        >Cancel</a
                      >
                    </td>
                  </template>
                </tr>
              </tbody>
            </table>
          </template>
        </div>
        <div class="modal-footer">
          <button
            v-if="modalType == 'Members'"
            data-dismiss="modal"
            class="btn gray"
            >Close</button
          >
          <template v-else>
            <button @click="saveModal" class="btn green">Save</button>
            <button data-dismiss="modal" class="btn gray">Cancel</button>
          </template>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  Kooboo.mailEditor = {};
</script>
<script>
  (function() {
    Kooboo.loadJS([
      "/_Admin/Scripts/components/kbTable.js",
      "/_Admin/Scripts/components/kbForm.js"
    ]);
  })();
  var self = new Vue({
    el: "#app",
    data: function() {
      var self = this;
      return {
        showModal: false,
        modalType: "",
        model: [],
        selectedRows: [],
        domains: [],
        normalModel: {
          local: "",
          addressType: "normal",
          domain: ""
        },
        normalModelRules: {
          local: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^[a-zA-Z0-9!#$%&+\-/=?^_`{|}~]+(\.[a-zA-Z0-9!#$%&+\-/=?^_`{|}~]+)*$/,
              message: Kooboo.text.validation.emailInvalid
            },
            {
              remote: {
                url: Kooboo.EmailAddress.isUniqueName(),
                data: function() {
                  return self.normalModel;
                }
              },
              message: Kooboo.text.validation.taken
            }
          ]
        },
        wildcardModel: {
          local: "",
          addressType: "wildcard",
          domain: ""
        },
        wildcardModelRules: {
          local: [
            {
              remote: {
                url: Kooboo.EmailAddress.isUniqueName(),
                data: function() {
                  return self.wildcardModel;
                }
              },
              message: Kooboo.text.validation.taken
            }
          ]
        },
        groupModel: {
          local: "",
          addressType: "group",
          domain: ""
        },
        groupModelRules: {
          local: [
            { required: Kooboo.text.validation.required },
            {
              remote: {
                url: Kooboo.EmailAddress.isUniqueName(),
                data: function() {
                  return self.groupModel;
                }
              },
              message: Kooboo.text.validation.taken
            }
          ]
        },
        forwardModel: {
          local: "",
          addressType: "forward",
          domain: "",
          forwardAddress: ""
        },
        forwardModelRules: {
          local: [
            { required: Kooboo.text.validation.required },
            {
              remote: {
                url: Kooboo.EmailAddress.isUniqueName(),
                data: function() {
                  return self.forwardModel;
                }
              },
              message: Kooboo.text.validation.taken
            }
          ],
          forwardAddress: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
              message: Kooboo.text.validation.emailInvalid
            }
          ]
        },
        updateForwardModel: {
          id: "",
          address: "",
          forwardAddress: ""
        },
        updateForwardModelRules: {
          forwardAddress: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
              message: Kooboo.text.validation.emailInvalid
            }
          ]
        },
        editingMember: false,
        members: [],
        selectedId: ""
      };
    },
    mounted: function() {
      var self = this;
      Kooboo.EmailAddress.Domains().then(function(res) {
        if (res.success) {
          self.domains = res.model;
          if (self.domains.length) {
            self.normalModel.domain = self.wildcardModel.domain = self.groupModel.domain = self.forwardModel.domain =
              self.domains[0].domainName;
          }
          self.refreshList();
        }
      });
    },
    methods: {
      onDelete: function() {
        var ids = this.selectedRows.map(function(m) {
          return m.id;
        });

        if (!confirm(Kooboo.text.confirm.deleteItems)) return;

        Kooboo[Kooboo.EmailAddress.name]
          .Deletes({
            ids: ids
          })
          .then(function(res) {
            if (res.success) {
              self.refreshList();
            }
          });
      },
      getInboxUrl: function(data) {
        return Kooboo.Route.Get(Kooboo.Route.Email.InboxPage, {
          address: data.address
        });
      },
      getUseFor: function(type) {
        if (type == "Group") {
          return {
            text: Kooboo.text.mail.address.groupMail,
            class: "label-sm blue"
          };
        } else if (type == "Forward") {
          return {
            text: Kooboo.text.mail.address.forwarding,
            class: "label-sm orange"
          };
        } else if (type == "Wildcard") {
          return {
            text: Kooboo.text.mail.address.wildcard,
            class: "label-sm green"
          };
        } else {
          return {
            text: Kooboo.text.mail.address.normal,
            class: "label-sm green"
          };
        }
      },
      getRemark: function(data) {
        if (data.addressType == "Group") {
          return {
            text:
              data.count +
              " " +
              Kooboo.text.mail[data.count > 1 ? "members" : "member"],
            type: "group",
            class: "label-sm blue"
          };
        } else if (data.addressType == "Forward") {
          return {
            text: Kooboo.text.mail.to + ": " + data.forwardAddress,
            class: "label-sm orange",
            type: "forward"
          };
        } else {
          return null;
        }
      },
      editModal: function(data) {
        self.selectedId = data.id;
        if (data.addressType == "Group") {
          self.modalType = "Members";
          Kooboo.EmailAddress.getMemberList({
            addressId: data.id
          }).then(function(res) {
            if (res.success) {
              self.members = res.model;
              self.modalType = "Members";
              self.showModal = true;
            }
          });
        } else {
          self.modalType = "EditForward";
          self.updateForwardModel.id = data.id;
          self.updateForwardModel.address = data.address;
          self.updateForwardModel.forwardAddress = data.forwardAddress;
        }
        self.showModal = true;
      },
      saveModal: function() {
        if (self.modalType == "Normal") {
          if (!self.$refs.normalForm.validate()) return;
          Kooboo.EmailAddress.post(JSON.stringify(this.normalModel)).then(
            function(res) {
              if (res.success) {
                self.refreshList();
                self.showModal = false;
              }
            }
          );
        } else if (self.modalType == "Wildcard") {
          if (!self.$refs.wildcardForm.validate()) return;
          Kooboo.EmailAddress.post(JSON.stringify(self.wildcardModel)).then(
            function(res) {
              if (res.success) {
                self.refreshList();
                self.showModal = false;
              }
            }
          );
        } else if (self.modalType == "Group") {
          if (!self.$refs.groupForm.validate()) return;
          Kooboo.EmailAddress.post(JSON.stringify(self.groupModel)).then(
            function(res) {
              if (res.success) {
                self.refreshList();
                self.showModal = false;
              }
            }
          );
        } else if (self.modalType == "Forward") {
          if (!self.$refs.forwardForm.validate()) return;
          Kooboo.EmailAddress.post(JSON.stringify(self.forwardModel)).then(
            function(res) {
              if (res.success) {
                self.refreshList();
                self.showModal = false;
              }
            }
          );
        } else if (self.modalType == "EditForward") {
          if (!self.$refs.editForwardForm.validate()) return;
          Kooboo.EmailAddress.updateForward(self.updateForwardModel).then(
            function(res) {
              if (res.success) {
                self.refreshList();
                self.showModal = false;
                window.info.show(Kooboo.text.info.update.success, true);
              } else {
                window.info.show(Kooboo.text.info.update.fail, false);
              }
            }
          );
        }
      },
      refreshList: function() {
        Kooboo.EmailAddress.getList().then(function(res) {
          if (res.success) {
            self.model = res.model;
            self.model.forEach(function(f) {
              f.useFor = self.getUseFor(f.addressType);
              f.remark = self.getRemark(f);
            });
          }
        });
      },
      removeMember: function(data) {
        Kooboo.EmailAddress.removeMember({
          addressId: self.selectedId,
          memberAddress: data
        }).then(function(res) {
          if (res.success) {
            self.members = self.members.filter(function(f) {
              return f != data;
            });
            self.refreshList();
          }
        });
      },
      saveMember: function(data) {
        data.posted = true;
        this.onMemberInput(data);
        if (data.error) return;
        Kooboo.EmailAddress.saveMember({
          addressId: self.selectedId,
          memberAddress: data.address
        }).then(function(res) {
          if (res.success) {
            self.members = self.members.filter(function(f) {
              return f != data;
            });
            self.members.push(res.model.memberAddress);
            self.editingMember = false;
            self.refreshList();
          }
        });
      },
      cancelMember: function(data) {
        self.editingMember = false;
        self.members = self.members.filter(function(f) {
          return f != data;
        });
      },
      onEditMember: function() {
        self.editingMember = true;
        self.members.push({
          address: "",
          error: "",
          posted: false,
          editing: true
        });
      },
      onMemberInput: function(data) {
        if (data.posted) {
          var result = Kooboo.validField(data.address, [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
              message: Kooboo.text.validation.emailInvalid
            }
          ]);
          data.error = result.msg;
        }
      }
    },
    watch: {
      modalType: function(value) {
        if (value) self.showModal = true;
      },
      showModal: function(value) {
        if (value) return;
        self.modalType = "";
        self.normalModel.local = "";
        self.wildcardModel.local = "";
        self.groupModel.local = "";
        self.forwardModel.local = "";
        self.forwardModel.forwardAddress = "";
        self.editingMember = false;
        self.members = [];
      }
    }
  });
</script>
